<template>
  <!--
    open 会在弹窗打开时触发!!!
   -->
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleClose"
    @open="handleOpen"
  >
    <!-- 这里准备复选框 -->
    <!-- ...{{ userId }} -->
    <!--
      el-checkbox-group 需要绑定的是一个数组  收集选择的项们
      el-checkbox 设置提示文字 直接用默认插槽提供!  收集提交的字段是label
      checkList能收集 也能设置默认选中项!!!
     -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in rolesList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>

    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickSubmit">确定</el-button>
      <el-button size="small">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetRolesList } from '@/api/settings' // 查询角色列表
import { reqGetUserDetail } from '@/api/user' // 带头像的接口
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // flag: true
      checkList: [],
      rolesList: [],
      loading: false
    }
  },
  created() {

  },
  methods: {
    handleClose() {
      this.$emit('update:showRoleDialog', false)
      // 关闭弹窗时 重置默认选中
      this.checkList = []
    },
    async getRolesList() {
      const { data: { rows }} = await reqGetRolesList(1, 999999)
      // console.log(res)
      this.rolesList = rows
    },
    async getUserDetail() {
      const { data: { roleIds }} = await reqGetUserDetail(this.userId)
      // console.log(res)
      this.checkList = roleIds
    },
    handleOpen() {
      // 请求并行
      this.loading = true
      // console.log('弹窗打开了...')
      // this.getRolesList() // 1s

      // this.getUserDetail() // 1s

      // 等所有promise都成功后 就会执行.then的回调
      // Promise.all([p1, p2, p3]).then((values) => { ... })

      // const p1 = this.getRolesList()
      // const p2 = this.getUserDetail()
      // console.log(p1, p2)
      // async函数的返回值就是一个promise

      // Promise.all([p1, p2]).then(() => {
      //   this.loading = false
      // })
      // 保证: 1.同时发出去的请求 2.请求都结束了 才会关闭loading
      Promise.all([this.getRolesList(), this.getUserDetail()]).then(() => {
        this.loading = false
      })
      // this.loading = false // 等两个请求都结束嘞 才关loading
    },
    async clickSubmit() {
      await reqAssignRoles({
        id: this.userId,
        roleIds: this.checkList
      })
      // console.log(res)
      this.$message.success('分配角色成功')
      this.handleClose()
    }
  }

}
</script>
